<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <el-page-header
          :content="`${id?'编辑企业':'添加企业'}`"
          @back="$router.back()"
        />
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" :model="addForm" :rules="rules" label-width="100px">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" placeholder="请选择行业">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload
                class="upload-demo"
                action="#"
                :http-request="uploadRequest"
                :before-upload="beforeUpload"
                list-type="picture-card"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>
    <el-form-item label="所在行业" prop="name">
      <el-select v-model="addForm.industryCode" />
    </el-form-item>
  </div>
</template>

<script>
import { getIndustryListAPI, uploadAPI, createExterpriseAPI, getEnterpriseDetailAPI, updateExterpriseAPI } from '@/api/Enterprise'
export default {
  data() {
    const validatePhone = (rule, value, callback) => {
      if (/^1[3-9]\d{9}$/.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正常的手机号'))
      }
    }
    return {
      industryList: [],
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      rules: {
        name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '请输入法人', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '请输入注册地址', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '请选择所在行业', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '请输入企业联系人', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        businessLicenseUrl: [
          { required: true, message: '请上传营业执照', trigger: 'change' }
        ]
      },
      fileList: [],
      id: this.$route.query.id || null,
      isEditMode: !!this.$route.query.id

    }
  },
  computed: {

  },
  mounted() {
    this.getIndustryList()
    if (this.isEditMode) {
      this.loadEnterpriseData()
    }
    if (this.Id) {
      this.etEnterpriseListAPI()
    }
  },
  methods: {
    async getEnterpriseListAPI() {
      const res = await getEnterpriseDetailAPI(this.rentId)
      const { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress } = res.data
      this.addForm = { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress }
    },
    async loadEnterpriseData() {
      if (!this.id) return
      const res = await getEnterpriseDetailAPI(this.id) // 调用企业详情的接口
      this.addForm = res.data // 将返回的接口数据赋值给表单

      // 初始化 fileList
      if (res.data.businessLicenseUrl) {
        this.fileList = [{
          name: '营业执照',
          url: res.data.businessLicenseUrl, // 直接使用完整URL
          uid: Date.now() // 添加唯一标识
        }]
      }

      console.log('初始化 fileList:', this.fileList)
    },
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传合同图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同图片大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    async getIndustryList() {
      const res = await getIndustryListAPI()
      this.industryList = res.data
    },
    async uploadRequest(data) {
      const file = data.file

      // 处理 formData 类型参数
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'businessLicense')

      console.log('上传的 formData:', formData)

      try {
        const res = await uploadAPI(formData)

        // 赋值表单数据
        this.addForm.businessLicenseId = res.data.id
        this.addForm.businessLicenseUrl = res.data.url

        // 更新 fileList
        this.fileList = [{ name: file.name, url: res.data.url }]

        // 单独校验表单处理错误信息
        this.$refs.ruleForm.validateField('businessLicenseId')
      } catch (error) {
        console.error('上传失败:', error)
        this.$message.error('上传失败，请稍后重试')
      }
    },
    // confirmSubmit() {
    //   this.$refs.ruleForm.validate(async valid => {
    //     console.log('表单验证结果', valid)
    //     // if (!valid) return
    //     // // 1. 调用接口
    //     // await createExterpriseAPI(this.addForm)
    //     // // 2. 返回列表页
    //     // this.$router.back()
    //     if (this.id) {
    //       // 编辑
    //       await updateExterpriseAPI({
    //         ...this.addForm,
    //         id: this.id
    //       })
    //     } else {
    //       // 创建
    //       await createExterpriseAPI(this.addForm)
    //     }
    //     this.$router.back()
    //   })
    // },
    confirmSubmit() {
      this.$refs.ruleForm.validate(async valid => {
        console.log(valid)
        if (this.id) {
          delete this.addForm.businessLicenseName
          delete this.addForm.industryName
          delete this.addForm.rent
          console.log('编辑的数据', this.addForm)
          // 编辑
          await updateExterpriseAPI(this.addForm)
        } else {
          // 新增
          await createExterpriseAPI(this.addForm)
        }
        this.$message.success(this.id ? '编辑成功' : '新增成功')
        this.$router.back()
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('提交成功!')
        } else {
          console.log('验证失败!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`)
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left:20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form{
          display: flex;
          flex-wrap: wrap;
          .el-form-item{
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
